﻿using Developer.Core.FrameWork.RedisExtensions.RedisSubscribeInit.Abstractions;
using Developer.Core.FrameWork.RedisExtensions.RedisSubscribeInit.Cache;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;

namespace Developer.Core.FrameWork.RedisExtensions.RedisSubscribeInit.InitMq
{
    public static class ServiceCollectionExtensions
    {
        public static InitMqBuilder AddInitRedisMq(this IServiceCollection services, Action<InitMqOption> setupAction)
        {
            if (setupAction == null)
                throw new ArgumentNullException(nameof(setupAction));
            InitMqOption options = new InitMqOption();
            setupAction(options);
            services.Configure<InitMqOption>(setupAction);
            services.AddSingleton(typeof(ICacheService), (object)new RedisCacheService(options.ConnectionString));
            services.AddHostedService<HostedService>();  // 核心，寄宿在aspnetcore的主机中
            if (options.ListSubscribe != null)
            {
                foreach (Type service in (IEnumerable<Type>)options.ListSubscribe)
                    services.TryAddSingleton(service);
                services.AddSingleton<Func<Type, IRedisSubscribe>>((Func<IServiceProvider, Func<Type, IRedisSubscribe>>)
                    (serviceProvider => (Func<Type, IRedisSubscribe>)
                    (key =>
                    {
                        foreach (Type serviceType in (IEnumerable<Type>)options.ListSubscribe)
                        {
                            if (key == serviceType)
                                return serviceProvider.GetService(serviceType) as IRedisSubscribe;
                        }
                        throw new ArgumentException(string.Format("不支持的DI Key: {0}", (object)key));
                    })));
            }
            return new InitMqBuilder(services);
        }
    }
}
